home *** CD-ROM | disk | FTP | other *** search
- Path: s02.pavilion.co.uk!usenet
- From: AJRobb@pavilion.co.uk (Andy J Robb)
- Newsgroups: comp.lang.c
- Subject: Re: revised code of calling a function twice from printf
- Date: Thu, 07 Mar 1996 06:25:46 GMT
- Organization: Pavilion Internet plc
- Message-ID: <4hlvfq$ja@s02.pavilion.co.uk>
- References: <4hfs54$k4e@newsbf02.news.aol.com>
- NNTP-Posting-Host: poolc24.pavilion.co.uk
- X-Newsreader: Forte Free Agent 1.0.82
-
- razine@aol.com (Razine) wrote:
-
- >Here is the actual code , modified with everyone's suggestions. However
- >there is still a bug in here somewhere. Can anyone please explain what is
- >wrong with this.
-
- >It returns
-
- >[1] NONE [2] NE
-
- >I would like it to return
-
- >[1] NONE [2] Asprin
-
- >Thank you very much for your help. it is greatly appreciated.
-
-
- >#include <stdio.h>
- >#include <string.h>
-
- >char *display_drug_type(int drug_index);
-
- >int drug_inventory[5]={0,1,0,0,0};
-
- >int main() {
-
- > printf("[1] %s [2] %s
- >\n",display_drug_type(0),display_drug_type(1));
-
- The problem is that you are returning pointers to strings that were on
- the stack. These strings will get re-used by the stack at some point.
- Two things you must do to make it work:
-
- 1) declare char drug_type[81] as static (below).
- 2) do not call the function twice in a single printf() call.
-
- printf("[1] %s ", display_drug_type(0));
- printf(" [2] %s\n", display_drug_type(1));
-
- >return 0;
- > }
-
- >char *display_drug_type(int drug_index) {
- > char drug_type[81]="\0";
-
- > switch(drug_inventory[drug_index]) {
- > case 0 : strcpy(drug_type,"NONE"); break;
- > case 1 : strcpy(drug_type,"Asprin"); break;
- > default : printf("Error in Display_drug_inventory");
- > }
- > return drug_type;
- >}
-
- Alternatively, a probably much safer (as well as faster, smaller etc.)
- routine that can be called as many times as you like in a printf():
-
- const char *display_drug_type(int drug_index)
- { switch(drug_index)
- { case 0:
- case 2:
- case 3:
- case 4: return "NONE";
- case 1: return "Asprin";
- }
-
- frintf(stderr, "Error in Display_drug_inventory\n");
- return "";
- }
-
- Note: I removed the drug_inventory[] as this could lead to general
- protection faults (crashes) for bad drug_index.
-
- Note: you should either place this code before main() or provide a
- function prototype before main().
-
- Regards,
- Andy Robb.
- -----BEGIN PGP PUBLIC KEY BLOCK-----
- Version: 2.6.2i
-
- mQCNAy/MpRwAAAEEAOt6uBYqT8yv9EmqNhK8m6v+bYi8QjnGW3Bo6iU1gsMj5pa6
- MHgq99c8deADbE3cbJ6uZS9v5pZE3WCf6HCQjlB5iULA5RZzMdAumd/WUzuL9UT3
- B44D9EqqFIL79FlYb56v4oKFqFp1/J2bIpYUwnUvabGzGjdLrpPl4P16x9sNAAUR
- tCNBbmR5IEogUm9iYiA8QUpSb2JiQHBhdmlsaW9uLmNvLnVrPrQhQW5keSBSb2Ji
- IDxBSlJvYmJAcGF2aWxpb24uY28udWs+
- =/wVD
- -----END PGP PUBLIC KEY BLOCK-----
-
-